import {
  addTenant,
  removeTenant,
  tenantList,
  updateTenant,
} from '@/services/ant-design-pro/tenantSet';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProFormText,
  ProFormUploadButton,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  //新建窗口的弹窗
  const [addModalOpen, handleAddModalOpen] = useState<boolean>(false);
  // 修改窗口的弹窗
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  //选择的修改数据
  const [selectUpdateTenant, setSelectUpdateTenant] = useState<API.TenantItem>({});
  //引用
  const actionRef = useRef<ActionType>();
  // 选择行
  const [selectedRowsState, setSelectedRows] = useState<API.TenantItem[]>([]);

  /**
     表格
     */

  const formatterTime = (time: any) => {
    return time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '';
  };

  const columns: ProColumns<API.TenantItem>[] = [
    {
      title: '租户ID',
      dataIndex: 'tenantId',
      key: 'tenantId',
    },
    {
      title: '租户名称',
      dataIndex: 'tenantName',
      key: 'tenantName',
    },
    {
      title: '上传时间',
      dataIndex: 'fileUploadTime',
      key: 'fileUploadTime',
      valueType: 'dateRange',
      render: (text, record) => formatterTime(record?.fileUploadTime),
    },
  ];
  columns.push({
    title: '操作',
    dataIndex: 'update',
    key: 'fileUploadTime',
    search: false,
    render: (text, record) => (
      <div>
        <Button
          type="link"
          onClick={() => {
            handleUpdateModalOpen(true);
            setSelectUpdateTenant(record);
          }}
        >
          重新上传文件
        </Button>
      </div>
    ),
  });

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.TenantItem) => {
    const hide = message.loading('正在添加');
    try {
      await addTenant({ ...fields });
      hide();
      message.success('新增成功');
      return true;
    } catch (error) {
      hide();
      message.error('新增失败，请稍后重试！');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const hide = message.loading('正在修改');
    try {
      await updateTenant({
        selectUpdateTenant,
        ...fields,
      });
      hide();

      message.success('修改成功');
      return true;
    } catch (error) {
      hide();
      message.error('修改失败, 新增失败，请稍后重试！!');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.TenantItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      await removeTenant({
        tenantIds: selectedRows.map((row) => row.tenantId),
      });
      hide();
      message.success('删除成功！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试！');
      return false;
    }
  };

  return (
    <PageContainer>
      {/* 表格 */}
      <ProTable<API.TenantItem, API.PageParams>
        headerTitle={'租户管理'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          //新建按钮
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleAddModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        // 查询的API
        request={tenantList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {/* 选中的批量操作 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <span>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      {/* 新增修改弹窗 */}
      <ModalForm
        title={'新增'}
        width="400px"
        open={addModalOpen}
        onOpenChange={handleAddModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.TenantItem);
          if (success) {
            handleAddModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="tenantName"
          label="租户名称"
          rules={[
            {
              required: true,
              message: '请填写租户名称',
            },
          ]}
          width="md"
        />
        <ProFormUploadButton
          name="dat"
          label="dat文件"
          rules={[{ required: true, message: '请上传文件' }]}
          max={1}
          accept=".dat"
        />
      </ModalForm>

      {/* 修改弹窗 */}
      <ModalForm
        title={'修改'}
        width="400px"
        open={updateModalOpen}
        initialValues={selectUpdateTenant}
        onOpenChange={handleUpdateModalOpen}
        onFinish={async (value) => {
          const success = await handleUpdate(value as API.TenantItem);
          if (success) {
            handleUpdateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormUploadButton
          name="dat"
          label="dat文件"
          rules={[{ required: true, message: '请上传文件' }]}
          max={1}
          accept=".dat"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
